package com.weiawei.net;


import com.weiawei.ui.PVPMainBoard;

import java.io.*;
import java.net.*;

public class Server extends NetContainer {
    private ServerSocket serverForClient;
    private Socket socketOnServer;
    private String localHostIP;
    private boolean isConnecting;
    private PVPMainBoard pvpMainBoard;

    /**
     * 服务器的构造函数
     *
     * @param pvpMainBoard 游戏主界面
     * @throws UnknownHostException 本地IP获取异常
     */
    public Server(PVPMainBoard pvpMainBoard) throws UnknownHostException, SocketException {
        this.localHostIP = getLocalHostIP();
        this.pvpMainBoard = pvpMainBoard;
    }


    /**
     * 获取本地IP地址
     *
     * @return 本地的IP地址
     */
    public String getLocalHostIP() throws UnknownHostException {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 更改服务器连接状态
     *
     * @param connecting 服务器的连接状态
     */
    public void setConnecting(boolean connecting) {
        isConnecting = connecting;
    }

    /**
     * 初始化IO流
     *
     * @throws IOException
     */
    @Override
    public void initIO() throws IOException {
        in = new DataInputStream(socketOnServer.getInputStream());
        out = new DataOutputStream(socketOnServer.getOutputStream());
    }

    /**
     * 服务器运行函数
     */
    @Override
    public void run() {
        try {
            serverForClient = new ServerSocket(1921);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socketOnServer = serverForClient.accept();
            initIO();
            isConnecting = true;
            if (isConnecting) {
                pvpMainBoard.getProcessLabel().setText("等待双方准备");
                pvpMainBoard.getButtonCreate().setVisible(false);
                pvpMainBoard.getButtonJoin().setVisible(false);
                pvpMainBoard.getButtonStart().setVisible(true);
                pvpMainBoard.getButtonBack().setVisible(true);
            }
            while (isConnecting) ;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接已断开");
            isConnecting = false;
        }
    }
}
